package com.wontube.smr.remote.m;

import java.util.ArrayList;
import java.util.List;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.core.annotation.CacheSupport;
import com.wontube.core.annotation.NoLoginSupport;
import com.wontube.core.pub.servlet.handlers.BasicHandler;
import com.wontube.smr.bo.LocationBO;
import com.wontube.smr.client.model.po.Country;
import com.wontube.smr.client.model.po.WebsiteLink;
import com.wontube.smr.client.model.vo.LocationInfo;
import com.wontube.smr.dao.bo.CountryDao;
import com.wontube.smr.dao.bo.WebsiteCategoryDao;
import com.wontube.smr.dao.bo.WebsiteLinkSelectDao;
import com.wontube.smr.web.client.m.IWebsiteLinkHandler;
import com.wontube.smr.web.client.model.vo.CateWebsiteLinks;
import com.wontube.smr.web.client.model.vo.MWebsiteLinkItems;

/**
 * @author tanggf(2012-6-6)
 *
 */
@NoLoginSupport
public class WebsiteLinkHandler extends BasicHandler implements IWebsiteLinkHandler {
	@Override
	@CacheSupport(timeToLiveSeconds=12 * 3600)
	public MWebsiteLinkItems  getWebsiteLinkHome(String countryCode, String sysId) {
		countryCode = remendCountCode(countryCode);		
		List<CateWebsiteLinks> list = new ArrayList<CateWebsiteLinks>();
		List<String> categories = WebsiteCategoryDao.listAllCategory(countryCode);
		for (String cate : categories) {
			List<WebsiteLink> links = WebsiteLinkSelectDao.listAllWebsiteLinks(countryCode, sysId, cate);
			CateWebsiteLinks catelinks = new CateWebsiteLinks();
			catelinks.setCategory(cate);
			catelinks.setLinks(links);
			
			list.add(catelinks);
		}
		MWebsiteLinkItems items = new MWebsiteLinkItems();
		items.setCategories(categories);
		items.setSysId(sysId);
		items.setCountryCode(countryCode);
		items.setCateWebsiteLinks(list);
		return items;
	}

	private String remendCountCode(String countryCode) {		
		if(StringUtils.isNullOrEmpty(countryCode)){
			String ip = super.getContext().getSession().getLastClientIP();
			LocationInfo location = LocationBO.getLocation(ip);			
			if(location != null){
				countryCode = location.getMapedCountryCode();
			}
		}
		
		if(countryCode == null){
			return Country.DEFAULT_COUNTRY_CODE;
		}
		
		countryCode = countryCode.toUpperCase();
		
		if( ! CountryDao.hasCountryCode(countryCode)){
			return Country.DEFAULT_COUNTRY_CODE;
		}	
		
		return countryCode;
	}

	@Override
	@CacheSupport(timeToLiveSeconds=12 * 3600)
	public List<WebsiteLink> listWontubePartnerSites() {
		return WebsiteLinkSelectDao.listWebsiteLinks("Website");
	}		
}
